# server/src/knowledge/file_parser.py
# 文件解析工具
import pdfplumber
from docx import Document as DocxDocument
import markdown
from io import BytesIO

class FileParser:
    """支持多种格式的文件解析"""
    
    def parse_file(self, file_content: bytes, filename: str) -> str:
        ext = filename.split('.')[-1].lower()
        
        if ext == 'pdf':
            return self._parse_pdf(file_content)
        elif ext == 'docx':
            return self._parse_docx(file_content)
        elif ext in ['md', 'markdown']:
            return self._parse_markdown(file_content)
        else:
            raise ValueError(f"不支持的格式: {ext}")

    def _parse_pdf(self, content: bytes) -> str:
        """解析PDF文件"""
        text = []
        with pdfplumber.open(BytesIO(content)) as pdf:
            for page in pdf.pages:
                text.append(page.extract_text())
        return "\n".join(text)

    def _parse_docx(self, content: bytes) -> str:
        """解析Word文档"""
        doc = DocxDocument(BytesIO(content))
        return "\n".join([p.text for p in doc.paragraphs])

    def _parse_markdown(self, content: bytes) -> str:
        """解析Markdown文件"""
        md_text = content.decode('utf-8')
        return markdown.markdown(md_text)